// aes_util.js
const CryptoJS = require('./aes.js'); //引用AES源码js 
const CryptoJSha256 = require('./sha256.js');  

var key = CryptoJS.enc.Hex.parse(CryptoJSha256.sha256_digest('123456'));//密钥
const iv  = CryptoJS.enc.Hex.parse('0000000000000000');//十六位十六进制数作为秘钥偏移量

/**
 * aes 加密方法
 */
function AesEncrypt(word) { 
  // Encrypt  
  let srcs = CryptoJS.enc.Utf8.parse(word);
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
    return encrypted.toString();
}
  
/**
 * aes 解密方法
 */
function AesDecrypt(word) { 
  let encryptedHexStr = CryptoJS.enc.Base64.parse(word);
  let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  let decrypt = CryptoJS.AES.decrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
} 
/**
 * base64 加密方法
 */
function Base64Encode(val) {
  let str = CryptoJS.enc.Utf8.parse(val);
  let base64 = CryptoJS.enc.Base64.stringify(str);
  return base64;
}

/**
 * base64 解密方法
 */
function Base64Decode(val) {
  let words = CryptoJS.enc.Base64.parse(val);
  return words.toString(CryptoJS.enc.Utf8);
} 
 

//暴露接口
module.exports = {
  AesDecrypt,
  AesEncrypt,
  Base64Encode,
  Base64Decode
}